const Sequelize = require("sequelize");

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  "postgres://postgres:password@localhost:6432/postgres";

async function makeSignup(signupReq) {
  //add user info
  let sz;
  if (signupReq.plan === "label") {
    sz = 0;
  } else if (signupReq.plan === "dev") {
    sz = 10737418240; //10GB
  } else if (signupReq.plan === "pro") {
    sz = 107374182400; //100GB
  } else {
    sz = 0;
  }
  try {
    var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});
    var res = await sequelize.query(
      "BEGIN;" +
        "INSERT INTO user_info(uid, storage_space) values (:userId, :size); " +
        "COMMIT;",
      {
        replacements: {
          userId: signupReq.id,
          size: sz
        }
      }
    );
    if (signupReq.plan == "dev" || signupReq.plan == "pro") {
      console.log("sign up start", signupReq);
      var res = await sequelize.query(
        "BEGIN;" +
          "INSERT INTO org_member(owner_id, user_id, name, role, state, create_by) values (:userId, :ownerId, :name, :role, :state, :createBy); " +
          "COMMIT;",
        {
          replacements: {
            userId: signupReq.id,
            ownerId: signupReq.id,
            name: signupReq.name,
            createBy: signupReq.id,
            role: "owner",
            state: "normal"
          }
        }
      );
      console.log("sign up ok");
      return res;
    }
  } catch (e) {
    console.log(e);
    throw new Error(e);
  } finally {
    sequelize.close();
  }
}

module.exports.makeSignup = makeSignup;
